﻿
using Castle.Core.Internal;
using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Microsoft.Extensions.Options;
using NetTopologySuite.Index.HPRtree;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlTypes;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Net;
using System.Reflection.Metadata;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using static org.apache.zookeeper.ZooDefs;

namespace Coldairarrow.Business.Interface
{
    public class RE_ReturnsInterfaceBusiness : REInterface_BaseBusiness, IJob_Business, ITransientDependency
    {
        //接口信息
        public Base_InterfaceOption RE_Query;
        public Base_InterfaceOption RE_Create;
        public RE_ReturnsInterfaceBusiness()
        {
            this.InterfaceName = "RE退货";
            //索引字段
            this.MapFields = GetMapField("RE_Query");
            //索引字段
            //Keys = GetKeys("addRow");

            //获取此接口的所有API信息
            this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
            //RE_Query = this.interfaceOption.Where(x => x.OperateType == "RE_Query").First();
            RE_Create = this.interfaceOption.Where(x => x.OperateType == "RE_Create").First();
            //查询执行前的事件
            this.BeforeQueryEvent += InterfaceBusiness_BeforeQueryEvent;
            //查询执行中的事件
            this.OnQueryEvent += InterfaceBusiness_OnQueryEvent;
            //查询执行中的事件
            this.AfterQueryEvent += InterfaceBusiness_AfterQueryEvent;


            //执行非查询请求中的事件
            this.OnNoQueryEvent += RE_OrderInfoInterfaceBusiness_OnNoQueryEvent; ;

            this.BeforeNoQueryEvent += RE_OrderInfoInterfaceBusiness_BeforeNoQueryEvent;

            this.AfterNoQueryEvent += RE_OrderInfoInterfaceBusiness_AfterNoQueryEvent;
        }

        /// <summary>
        /// 执行非查询请求前事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="RE_NoQueryEventArgs"></param>
        private void RE_OrderInfoInterfaceBusiness_BeforeNoQueryEvent(object sender, RE_NoQueryEventArgs noQueryEventArgs)
        {
            try
            {
                //获取appId
                RE_BaseReqDTO RE_BaseReq = new RE_BaseReqDTO();
                noQueryEventArgs.CustomData = RE_BaseReq;
                //获取配置参数
                this.SqlDb._conStrings[0] = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
                var parameters = this.SqlDb.GetListBySql<Base_ConfigParameter>(@$"SELECT * FROM  Base_ConfigParameter(NOLOCK) WHERE Code='RE'");
                RE_BaseReq.AppKey = parameters.Where(x => x.Name == "appKey").First().Value;
                RE_BaseReq.AppToken = parameters.Where(x => x.Name == "appToken").First().Value;
                RE_BaseReq.SoapEnv = parameters.Where(x => x.Name == "SoapEnv").First().Value;
                RE_BaseReq.Ns1 = parameters.Where(x => x.Name == "Ns1").First().Value;
                RE_BaseReq.Service = RE_Create.InterfaceType;
            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }

        /// <summary>
        /// 执行非查询请求中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="RE_NoQueryEventArgs"></param>
        private void RE_OrderInfoInterfaceBusiness_OnNoQueryEvent(object sender, RE_NoQueryEventArgs noQueryEventArgs)
        {
            //XML格式的参数
            RE_BaseReqDTO RE_BaseReq = (RE_BaseReqDTO)noQueryEventArgs.CustomData;
            //json参数
            //PL_ReqDTO_PushOrder data = new PL_ReqDTO_PushOrder();
            //data = (PL_ReqDTO_PushOrder)noQueryEventArgs.Data;
            //data.date_from = DateTime.Now.AddDays(-queryEventArgs.Page.Total).ToString("yyyy-MM-dd");
            //data.date_to = DateTime.Now.ToString("yyyy-MM-dd");
            RE_BaseReq.ParamsJson = GetJsonData(noQueryEventArgs.APINodes, noQueryEventArgs.ParentNode, noQueryEventArgs.Data);
            //获取请求的XML字符串
            noQueryEventArgs.reqData = GetRequstXML(RE_BaseReq);
        }
        /// <summary>
        /// 执行非查询请求后事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="RE_NoQueryEventArgs"></param>
        private void RE_OrderInfoInterfaceBusiness_AfterNoQueryEvent(object sender, RE_NoQueryEventArgs noQueryEventArgs)
        {
            RE_ReqDTO_Return data = (RE_ReqDTO_Return)noQueryEventArgs.Data;
            try
            {
                //获取返回XML中的JSON结果
                var res = GetXMLResponse(noQueryEventArgs.ResultStr, (RE_BaseReqDTO)noQueryEventArgs.CustomData);
                //将查询后的数据转换成对应格式的数据
                RE_ResDTO_Return result = (RE_ResDTO_Return)JsonConvert.DeserializeObject<RE_ResDTO_Return>(res);
                //将查询后的数据转换成对应格式的数据
                //RE_ResDTO_Order result = (RE_ResDTO_Order)JsonConvert.DeserializeObject<RE_ResDTO_Order>(noQueryEventArgs.ResultStr);
                if (result.ask == "Success")
                {
                    data.ResultMsg = result.return_code;
                    //this.NoQueryMsg.Add(data.reference_code + "推送成功");
                    noQueryEventArgs.Page.Complete = true;
                    noQueryEventArgs.Success = true;
                    //noQueryEventArgs.Rows = result.data.IsNullOrEmpty() ? null : result.data.list;
                }
                else
                {
                    noQueryEventArgs.Success = false;
                    data.ResultMsg = "推送失败,失败消息" + $":{data.reference_no}" + $":{result.message}";
                    //this.NoQueryMsg.Add(data.reference_code + "推送失败,失败消息" + $":{result.message}");
                }

            }
            catch (Exception ex)
            {
                noQueryEventArgs.Success = false;
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
                data.ResultMsg = "推送失败,失败消息" + $":{data.reference_no}" + $":{ex.Message}";
                //this.NoQueryMsg.Add(data.reference_code + "推送失败,失败消息" + $":{ex.Message}");
            }
        }



        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private async void InterfaceBusiness_BeforeQueryEvent(object sender, RE_QueryEventArgs queryEventArgs)
        {
            try
            {
                //获取appId
                RE_BaseReqDTO RE_BaseReq = new RE_BaseReqDTO();
                queryEventArgs.CustomData = RE_BaseReq;
                //获取配置参数
                this.SqlDb._conStrings[0] = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
                var parameters = this.SqlDb.GetListBySql<Base_ConfigParameter>(@$"SELECT * FROM  Base_ConfigParameter(NOLOCK) WHERE Code='RE'");
                RE_BaseReq.AppKey = parameters.Where(x => x.Name == "appKey").First().Value;
                RE_BaseReq.AppToken = parameters.Where(x => x.Name == "appToken").First().Value;
                RE_BaseReq.SoapEnv = parameters.Where(x => x.Name == "SoapEnv").First().Value;
                RE_BaseReq.Ns1 = parameters.Where(x => x.Name == "Ns1").First().Value;
                RE_BaseReq.Service = RE_Query.InterfaceType;
                //设置单次查询的页面数量
                queryEventArgs.Page.PageSize = queryEventArgs.APINodes.Where(x => x.TargetField == "pageSize").First().SourceField.ToInt();
                //设置需要查询多久之前的数据
                //queryEventArgs.Page.Total = queryEventArgs.APINodes.Where(x => x.TargetField == "create_date_from").First().Notes.ToInt();
                queryEventArgs.Page.PageIndex = 1;
            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }

        /// <summary>
        /// 查询中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_OnQueryEvent(object sender, RE_QueryEventArgs queryEventArgs)
        {
            //XML格式的参数
            RE_BaseReqDTO RE_BaseReq = (RE_BaseReqDTO)queryEventArgs.CustomData;
            //json参数
            RE_ReqDTO data = new RE_ReqDTO();
            data.page = queryEventArgs.Page.PageIndex;
            //data.date_from = DateTime.Now.AddDays(-queryEventArgs.Page.Total).ToString("yyyy-MM-dd");
            //data.date_to = DateTime.Now.ToString("yyyy-MM-dd");
            RE_BaseReq.ParamsJson = GetJsonData(queryEventArgs.APINodes, queryEventArgs.ParentNode, data);
            //获取请求的XML字符串
            queryEventArgs.reqData = GetRequstXML(RE_BaseReq);
        }

        /// <summary>
        /// 查询执行后的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_AfterQueryEvent(object sender, RE_QueryEventArgs queryEventArgs)
        {

            try
            {
                //获取返回XML中的JSON结果
                var res = GetXMLResponse(queryEventArgs.ResultStr, (RE_BaseReqDTO)queryEventArgs.CustomData);
                //将查询后的数据转换成对应格式的数据
                RE_BaseResponseDTO<RE_ProductInventory> result = (RE_BaseResponseDTO<RE_ProductInventory>)JsonConvert.DeserializeObject<RE_BaseResponseDTO<RE_ProductInventory>>(res);
                if (result.ask == "Success")
                {
                    queryEventArgs.Success = true;
                    if (!result.nextPage)
                    {
                        //查询完成
                        queryEventArgs.Page.PageIndex = 1;
                        queryEventArgs.Page.Complete = true;
                        if (result.data.Count > 0) queryEventArgs.Rows = result.data;
                    }
                    else
                    {
                        //查询下一页
                        queryEventArgs.Page.PageIndex += 1;
                        queryEventArgs.Rows = result.data;
                    }
                }
                else
                { queryEventArgs.Success = false; }

            }
            catch (Exception ex)
            {
                queryEventArgs.Success = false;
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }

        }

        /// <summary>
        /// 执行增删改查业务
        /// </summary>
        //public async void ExecuteInterface()
        //{
        //    List<RE_ProductInventory> invList = await this.QueryAsync<RE_ProductInventory>(this.RE_Query, SqlDb);



        //}

        /// <summary>
        /// 执行增删改查业务
        /// </summary>
        public async void ExecuteInterface()
        {

            try
            {
                List<RE_ReqDTO_Order> pL_ReqDTO_PushOrders = new List<RE_ReqDTO_Order>();
                RE_ReqDTO_Order pL_ReqDTO = new RE_ReqDTO_Order();
                pL_ReqDTO.platform = "OZON";
                pL_ReqDTO.allocated_auto = "0";
                pL_ReqDTO.warehouse_code = "MSK";
                pL_ReqDTO.shipping_method = "SELF-DELIVERY";
                pL_ReqDTO.reference_no = "ref_1399867104";
                pL_ReqDTO.aliexpress_order_no = "8000777788889999";
                pL_ReqDTO.order_desc = "TEST";
                pL_ReqDTO.remark = "我是备注";
                pL_ReqDTO.order_business_type = "b2c";
                pL_ReqDTO.country_code = "RU";
                pL_ReqDTO.city = "city";
                pL_ReqDTO.district = "收件人区";
                pL_ReqDTO.address1 = "address1";
                pL_ReqDTO.address2 = "address1";
                pL_ReqDTO.address3 = "address1";
                pL_ReqDTO.zipcode = "142970";
                pL_ReqDTO.license = "420904";
                pL_ReqDTO.doorplate = "doorplate";
                pL_ReqDTO.company = "company";
                pL_ReqDTO.name = "name";
                pL_ReqDTO.phone = "12345";
                pL_ReqDTO.cell_phone = "12345";
                pL_ReqDTO.phone_extension = "";
                pL_ReqDTO.email = "";
                pL_ReqDTO.platform_shop = "shop";
                pL_ReqDTO.is_order_cod = "0";
                pL_ReqDTO.order_cod_price = "0";
                pL_ReqDTO.order_cod_currency = "RMB";
                pL_ReqDTO.is_signature = "0";
                pL_ReqDTO.is_insurance = "0";
                pL_ReqDTO.insurance_value = "0";
                pL_ReqDTO.channel_code = "demo";
                pL_ReqDTO.assign_date = "2025-11-01";
                pL_ReqDTO.assign_time = "00";
                pL_ReqDTO.items = new List<RE_ReqDTO_Order.Items>();
                RE_ReqDTO_Order.Items item = new RE_ReqDTO_Order.Items();

                item.product_sku = "TEST001";
                item.reference_no = "149H6286";
                item.product_name_en = "Product";
                item.product_name = "Product";
                item.product_declared_value = "5.000";
                item.quantity = 1;
                item.ref_tnx = "1495099983020";
                item.ref_item_id = "302588235574";
                item.ref_buyer_id = "esramo_a62szxok";
                item.already_taxed = "I_TAXED";
                item.child_order_id = "child_order_id";
                pL_ReqDTO.items.Add(item);
                pL_ReqDTO_PushOrders.Add(pL_ReqDTO);
                await this.ExecuteNoQuery<RE_ReqDTO_Order>(pL_ReqDTO_PushOrders, this.RE_Create, this.SqlDb);
            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }



        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }

        /// <summary>
        /// 获取请求的XML格式字符串
        /// </summary>
        public string GetRequstXML(RE_BaseReqDTO reqDTO)
        {
            string soapXml = "";
            if (!reqDTO.IsNullOrEmpty())
            {
                // 1. 创建XDocument
                XNamespace soapEnv = reqDTO.SoapEnv;
                XNamespace ns1 = reqDTO.Ns1;

                XDocument soapRequest = new XDocument(
                    new XDeclaration("1.0", "UTF-8", null),
                    new XElement(soapEnv + "Envelope",
                        new XAttribute(XNamespace.Xmlns + "SOAP-ENV", soapEnv),
                        new XAttribute(XNamespace.Xmlns + "ns1", ns1),
                        new XElement(soapEnv + "Body",
                            new XElement(ns1 + "callService",
                                new XElement("paramsJson", reqDTO.ParamsJson),
                                new XElement("appToken", reqDTO.AppToken),
                                new XElement("appKey", reqDTO.AppKey),
                                new XElement("service", reqDTO.Service)
                            )
                        )
                    )
                );
                // 2. 转换为字符串
                soapXml = soapRequest.ToString();
            }
            return soapXml;

        }


        /// <summary>
        /// 获取返回XML的json结果
        /// </summary>
        public string GetXMLResponse(string xmlString, RE_BaseReqDTO reqDTO)
        {
            string res = "";
            if (!reqDTO.IsNullOrEmpty() && xmlString.Contains("\"ask\":"))
            {
                XDocument xdoc = XDocument.Parse(xmlString);
                XNamespace soapEnv = reqDTO.SoapEnv;
                XNamespace ns1 = reqDTO.Ns1;

                // 获取response标签的内容
                res = xdoc
                    .Element(soapEnv + "Envelope")
                    .Element(soapEnv + "Body")
                    .Element(ns1 + "callServiceResponse")
                    .Element("response")?
                    .Value;
            }
            return res;

        }
    }

}
